/**
 * 日志中间件
 * 记录请求和响应信息
 */
const logger = require('koa-logger');

/**
 * 配置日志中间件
 * @returns {Function} 日志中间件函数
 */
const loggerMiddleware = () => {
  // 开发环境使用详细日志
  if (process.env.NODE_ENV === 'development') {
    return logger((str, args) => {
      // 自定义日志格式
      const [format, method, url, status, time, length] = args;
      const timestamp = new Date().toISOString();
      console.log(`[${timestamp}] ${method} ${url} - ${status} ${time} ${length || ''}`);
    });
  }
  
  // 生产环境使用简化日志
  return async (ctx, next) => {
    const start = Date.now();
    await next();
    const ms = Date.now() - start;
    
    // 只记录错误和重要信息
    if (ctx.status >= 400) {
      console.log(`[${new Date().toISOString()}] ${ctx.method} ${ctx.url} - ${ctx.status} ${ms}ms`);
    }
  };
};

/**
 * 自定义日志工具
 */
const log = {
  info: (message, data = null) => {
    console.log(`[INFO] [${new Date().toISOString()}] ${message}`, data ? JSON.stringify(data, null, 2) : '');
  },
  
  error: (message, error = null) => {
    console.error(`[ERROR] [${new Date().toISOString()}] ${message}`, error ? error.stack || error : '');
  },
  
  warn: (message, data = null) => {
    console.warn(`[WARN] [${new Date().toISOString()}] ${message}`, data ? JSON.stringify(data, null, 2) : '');
  },
  
  debug: (message, data = null) => {
    if (process.env.NODE_ENV === 'development') {
      console.log(`[DEBUG] [${new Date().toISOString()}] ${message}`, data ? JSON.stringify(data, null, 2) : '');
    }
  }
};

module.exports = {
  loggerMiddleware,
  log
};